﻿using PoznanEvents.Events;
using PoznanEvents.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Xml.Linq;


namespace PoznanEvents.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {

        public EventModel _eventModel;
        public event EventHandler<EventArgs> CloseLoadingBar;
        public event EventHandler<EventArgs> ShowInterNetConnectionFaildAlert;
        public event EventHandler<EventArgs> ShowApplicationBar;
        public event EventHandler<EventArgs> ShowSearch;
        public DateTime StartDate;
        public DateTime EndDate;
        public string SearchText;
        private XDocument ResultXDocument;
        private IEnumerable<Event> AllEventData;
        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public bool IsDataChanged = false;

        public MainViewModel()
        {
            StartDate = DateTime.Now;
            EndDate = StartDate.AddDays(7);
            _eventModel = new EventModel();
            _eventModel.EventsRangeDateCompleted += EventsRangeDateCompleted;
        }



        #region view binding items

        private Event _selectedEvent;
        public Event SelectedEvent
        {
            get { return _selectedEvent; }
            set
            {
                if (value != null)
                {
                    _selectedEvent = value;
                    NotifyPropertyChanged("SelectedEvent");
                }
            }

        }

        private ObservableCollection<Event> events;
        public ObservableCollection<Event> Events
        {
            get
            {
                return events;
            }
            set
            {
                events = value;
                NotifyPropertyChanged("Events");

            }
        }
        #endregion

        #region events
        public void EventsRangeDateCompleted(object sender, getEventsCompletedEventArgs args)
        {
            try
            {
                ResultXDocument = XDocument.Parse(args.Result.@return.ToString());
                SetEvents();
            }
            catch (NullReferenceException err)
            {
                ShowInterNetConnectionFaildAlert(this, new EventArgs());
            }
            catch (System.Exception err)
            {
                ShowInterNetConnectionFaildAlert(this, new EventArgs());
            }
        }
        #endregion

        #region helper

        public void LoadData()
        {
            try
            {
                _eventModel.GetDataDateRange(StartDate, EndDate);
            }
            catch (NullReferenceException err)
            {
                MessageBox.Show("Brak połączenia z internetem");
            }
            catch (System.Exception err)
            {
                MessageBox.Show("Brak połączenia z internetem");
            }
        }

        public void LoadLocalData()
        {
            var events = from Event _event in AllEventData
                         where _event.EventDateStart > StartDate && _event.EventDateStart < EndDate
                         orderby _event.EventDateStart
                         select _event;

            if (!String.IsNullOrEmpty(SearchText))
            {
                events = from Event _event in AllEventData
                             where _event.EventDateStart > StartDate && _event.EventDateStart < EndDate
                             && _event.EventVersion.ToLower().Contains(SearchText.ToLower())
                             orderby _event.EventDateStart
                             select _event;
            }

            Events = new ObservableCollection<Event>(events);

            var eventsWitLocalization = from Event _event in events
                                        where _event.EventLongitue != 0 || _event.EventLatitude != 0
                                        select _event;

            //LoadPansToMap(this, new MapPansEvenArgs(new ObservableCollection<Event>(eventsWitLocalization)));
            IsDataChanged = false;
            CloseLoadingBar(this, new EventArgs());
            ShowApplicationBar(this, new EventArgs());
            ShowSearch(this, new EventArgs());
        }

        public void ClearAllData()
        {
            Events = new ObservableCollection<Event>();
        }

        private void SetEvents()
        {
            AllEventData = from e in ResultXDocument.Descendants("event")
                           orderby e.Element("event_start").Value
                           select new Event(e.Element("event_id"), e.Element("event_author"), e.Element("event_address"), e.Element("event_start"),
                                 e.Element("event_end"), e.Element("event_url"), e.Element("event_version"), e.Element("event_keywords"));
            IsDataLoaded = true;
            LoadLocalData();
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}